#!/usr/bin/python
# coding=utf-8

import mop
import moplist
import partylist
import party as partymodule
import os
import time
from openpolitics.models import *
from django.db.models import Q
from django.template.defaultfilters import slugify
from helpers import *

img_path = ''

def main():
    pass

person_dataitems = {
  'url': (DataType.objects.get(name='source_senatgovpl_page_url'), 'path'),
  'imgurl': (DataType.objects.get(name='source_senatgovpl_img_url'), 'img'),
  'imgpath': (DataType.objects.get(name='source_senatgovpl_img_path'), None),
  'email': (DataType.objects.get(name='source_senatgovpl_email'), 'email'),
  'www': (DataType.objects.get(name='source_senatgovpl_www'), 'www'),
}

party_dataitems = {
  'url': (DataType.objects.get(name='source_senatgovpl_page_url'), 'path'),
  'email': (DataType.objects.get(name='source_senatgovpl_email'), 'email'),
  'www': (DataType.objects.get(name='source_senatgovpl_www'), 'www'),
}

poland = State.objects.get(shortname='Polska')
chamber = InstitutionType.objects.get(name='Chamber')
party = InstitutionType.objects.get(name='Party')
deputy_type = PositionType.objects.get(name='Deputy', institution=chamber)
member_type = PositionType.objects.get(name='Member', institution=party)
senat = Institution.objects.get(name='Senat', type=chamber)
deputy = Position.objects.get(type=deputy_type, institution=senat)


def reload_member_list(chunk=20,
                       start=0,
                       bufobj=None,
                       sleep=1):
    path = 'http://www.senat.gov.pl/k7/senat/senator.htm'
    # one load is for memberlist url
    buffer=0

    if bufobj is None:
        people = moplist.get_members(path)
        buffer=1
    else:
        people = bufobj    
    i=start
    for person in people[start:chunk+start-buffer]:
        po = find_person(None, person['url'])
        if po:
            buffer += 1
            continue
        po = Person(first_name=person['first_name'],
                    last_name=person['last_name'],
                    slug=slugify('%s %s' % (person['first_name'], person['last_name'])))
        po.save()
        n1 = Nationality(person=po, state=poland)
        n1.save()
        i+=1
        reload_member(person['url'], po, i)
        buffer+=1
        time.sleep(1)

    return (buffer-1 if bufobj is None else buffer,
            people)

def reload_member(path, po=None, i=None):
    print 'Member %s' % i
    mo = mop.get_member(path)
    name = Name(object=po) if po else None
    if not po:
        po = find_person(name, path)
    if not po:
        name = split_name(mo['name'])
        po = Person(first_name=name['first'],
                    last_name=name['last'],
                    slug=slugify('%s %s' % (name['first'], name['last'])))
        po.save()
        po.nationalities.add(poland)

    try:
        t = po.positions.get(pk=deputy.pk)
    except Position.DoesNotExist, e:
        t = Term(position=deputy,
                 person=po)
        t.save()
    for elem in person_dataitems.values():
        if elem[1] is None or mo[elem[1]] is None:
            continue
        try:
            di = po.data.get(type=elem[0])
            if di.value != mo[elem[1]]:
                di.value = mo[elem[1]]
                di.save()
        except DataItem.DoesNotExist, e:
            po.data.create(type=elem[0], value=mo[elem[1]])
        except DataItem.MultipleObjectsReturned, e:
            po.data.filter(type=elem[0]).delete()
            po.data.create(type=elem[0], value=mo[elem[1]])

def reload_parties():
    #Institution.objects.filter(type=party, parents=poland).delete()
    parties = partylist.get_parties()
    for p in parties:
        po = find_party(p['shortname'])
        if po:
            reload_party(p['members_url'], po=po)
    return (0, None)

def reload_party(path, po=None):
    pdata = partymodule.get_party(path)
    reload_party_affiliates(pdata['members'], po)

def reload_party_affiliates(members, po):
    fo = Position.objects.get(type=member_type, institution=po)
    for member in members:
        person = find_person(None, member['url'])
        t, c = Term.objects.get_or_create(person=person,
                                          position=fo)

def reload(chunk=20,
           start=0,
           bufobj=None,
           sleep=1):
    #reload_member('http://sejm.gov.pl/poslowie/posel6/001.htm')
    ret = reload_member_list(chunk=chunk,
                             start=start,
                             bufobj=bufobj,
                             sleep=sleep)
    if ret[0] == 0:
        ret2 = reload_parties()
    return ret
    #po = Group.objects.get(shortname='PSL')
    #reload_party_affiliates('http://sejm.gov.pl/poslowie/kluby/pos_psl.htm', po)
    

if __name__ == "__main__":
    reload()
